package jp.co.dailyReport.weeklyReport.action;

import java.io.IOException;
import java.util.Calendar;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import jp.co.dailyReport.DataUnavailableException;
import jp.co.dailyReport.Utilities;
import jp.co.dailyReport.SystemCalendar;
import jp.co.dailyReport.staff.Staff;
import jp.co.dailyReport.staff.StaffManager;
import jp.co.dailyReport.project.Project;
import jp.co.dailyReport.project.ProjectManager;
import jp.co.dailyReport.project.PjStaff;
import jp.co.dailyReport.project.PjStaffManager;
import jp.co.dailyReport.workItem.WorkItem;
import jp.co.dailyReport.workItem.WorkItemManager;
import jp.co.dailyReport.weeklyReport.WeeklyReport;
import jp.co.dailyReport.weeklyReport.WeeklyReportManager;
import jp.co.dailyReport.weeklyReport.WeeklyReportWorkItem;
import jp.co.dailyReport.weeklyReport.WeeklyReportWorkItemManager;

/**
 * 週報登録のプロジェクト名、作業期間入力ページのボタン（登録、削除）
 * が押されたときの処理を管理するクラスです。
 */
public class WeeklyReportAddAction extends Action {

	private static Logger log = Logger.getLogger(WeeklyReportAddAction.class);

	/**
	 * 週報登録のプロジェクト名、作業期間入力ページのボタン（登録、削除）が押されたときの処理を実行します。<BR><BR>
	 * 「登録」ボタンが押された場合の処理：<BR>
	 * プロジェクトIDと作業期間から週報情報を取得し、週報情報があるならば、DynaActionFormオブジェクトの
	 * フィールドに設定します。<BR>
	 * プロジェクトIDと作業期間から週報作業項目情報を取得し、セッションに設定します。<BR>
	 * プロジェクトIDから作業項目情報を取得し、セッションに設定します。<BR><BR>
	 * 「削除」ボタンが押された場合の処理：<BR>
	 * プロジェクトIDと作業期間から週報情報を取得し、週報情報があるならば、DynaActionFormオブジェクトの
	 * フィールドに設定します。<BR>
	 * 週報情報がないならば、リクエストにエラーメッセージが設定されます。
	 * 週報IDから週報作業項目情報を取得し、作業項目IDから作業項目情報を取得します。
	 * 
	 * @param mapping このインスタンスを選択するために使用したActionMapping
	 * @param form 存在するならば、このリクエストのためのActionForm Bean
	 * @param request 処理しているHTTPリクエスト
	 * @param response 処理しているHTTPレスポンス
	 * @return ActionForwardインスタンス
	 * @throws IOException, ServletException
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

		log.debug("WeeklyReportAddAction start");
		HttpSession session = request.getSession();
		log.debug("session.getId() = " + session.getId());
		Staff staff = (Staff)session.getAttribute("LoginStaff");
		SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
		DynaActionForm doWeeklyReportActionForm = (DynaActionForm)form;
		String target = null;

		Calendar workDateEnd = Utilities.getEWeekCalendarDate(
		(Integer)doWeeklyReportActionForm.get("workDateStartY"), 
		(Integer)doWeeklyReportActionForm.get("workDateStartM"), 
		(Integer)doWeeklyReportActionForm.get("workDateStartW"));
		doWeeklyReportActionForm.set("workDateEndY", new Integer(workDateEnd.get(Calendar.YEAR)));
		doWeeklyReportActionForm.set("workDateEndM", new Integer(workDateEnd.get(Calendar.MONTH)+1));
		doWeeklyReportActionForm.set("workDateEndD", new Integer(workDateEnd.get(Calendar.DATE)));

		Calendar workDateStart = Utilities.getSWeekCalendarDate(
		(Integer)doWeeklyReportActionForm.get("workDateStartY"), 
		(Integer)doWeeklyReportActionForm.get("workDateStartM"), 
		(Integer)doWeeklyReportActionForm.get("workDateStartW"));
		workDateStart.add(Calendar.DATE , -2);
		doWeeklyReportActionForm.set("workDateStartY", new Integer(workDateStart.get(Calendar.YEAR)));
		doWeeklyReportActionForm.set("workDateStartM", new Integer(workDateStart.get(Calendar.MONTH)+1));
		doWeeklyReportActionForm.set("workDateStartD", new Integer(workDateStart.get(Calendar.DATE)));

		Project project = null;
		Staff pLStaff = null;
		Staff[] staffList = null;
		try {
			int projectId = ((Integer)doWeeklyReportActionForm.get("projectId")).intValue();
			WeeklyReport weeklyReport = WeeklyReportManager.load(projectId,workDateStart,workDateEnd);
			if(request.getParameter("add") != null) {
				target = addWeeklyReport(doWeeklyReportActionForm,request,weeklyReport,workDateStart,workDateEnd);
				log.debug("add or update----" + "staffId : " + staff.getStaffId() + " workDateStart : " + df.format(workDateStart.getTime()) + " workDateEnd : " + df.format(workDateEnd.getTime()));
			}else if(request.getParameter("rm") != null) {
				target = rmWeeklyReport(doWeeklyReportActionForm,request,weeklyReport);
				log.debug("rm----" + "staffId : " + staff.getStaffId() + " workDateStart : " + df.format(workDateStart.getTime()) + " workDateEnd : " + df.format(workDateEnd.getTime()));
			}
			project = ProjectManager.load(projectId);
			pLStaff = StaffManager.load(project.getPLStaffId());
			PjStaff[] pjStaff = PjStaffManager.getStaffId(projectId);
			staffList = new Staff[pjStaff.length];
			for(int i = 0; i < pjStaff.length; i++) {
				staffList[i] = StaffManager.load(pjStaff[i].getStaffId());
			}
			request.setAttribute("allStaffList", StaffManager.load());
		} catch(DataUnavailableException due) {
			log.error(due.getMessage());
		}
		request.setAttribute("project", project);
		request.setAttribute("pLStaff", pLStaff);
		request.setAttribute("staffList", staffList);
		log.debug("WeeklyReportAddAction end");
		return mapping.findForward(target);
	}

	private String addWeeklyReport(DynaActionForm doWeeklyReportActionForm, HttpServletRequest request,WeeklyReport weeklyReport,Calendar workDateStart,Calendar workDateEnd) {

		HttpSession session = request.getSession();
		int projectId = ((Integer)doWeeklyReportActionForm.get("projectId")).intValue();
		int weeklyReportId = weeklyReport.getWeeklyReportId();
		Vector vec = new Vector();
		WorkItem[] workItemList = null;
		if(weeklyReportId!=0){
			doWeeklyReportActionForm.set("weeklyReportId", new Integer(weeklyReportId));
			doWeeklyReportActionForm.set("problem",weeklyReport.getProblem());
			doWeeklyReportActionForm.set("comment",weeklyReport.getComment());
		}
		try {
			workItemList = WorkItemManager.loadPId(projectId);
			WeeklyReportWorkItem[] weeklyReportWorkItems = WeeklyReportWorkItemManager.load(projectId,workDateStart,workDateEnd);
			for(int i = 0; i < workItemList.length; i++) {
				if(workItemList[i].getDeadline()==null){
					workItemList[i].setDeadline(Calendar.getInstance());
				}
				int flg = 0;
				int workItemId = workItemList[i].getWorkItemId();
				for(int j = 0; j < weeklyReportWorkItems.length; j++) {
					if(workItemId==weeklyReportWorkItems[j].getWorkItemId()){
						vec.add(weeklyReportWorkItems[j]);
						flg++;
					}
				}
				if(flg==0) {
					WeeklyReportWorkItem weeklyReportWorkItem = new WeeklyReportWorkItem();
					weeklyReportWorkItem.setWorkItemId(workItemId);
					weeklyReportWorkItem.setWorkingHours(0);
					vec.add(weeklyReportWorkItem);
				} 
			}
		} catch(DataUnavailableException due) {
			log.error(due.getMessage());
		}
		session.setAttribute("workItemList", workItemList);
		session.setAttribute("weeklyReportWorkItem", (WeeklyReportWorkItem[])vec.toArray(new WeeklyReportWorkItem[0]));
		request.setAttribute("systemCalendar", new SystemCalendar());
		session.setAttribute("addWorkItemList", new Vector());
		session.setAttribute("addWeeklyReportWorkItemList", new Vector());
		return "add";
	}

	private String rmWeeklyReport(DynaActionForm doWeeklyReportActionForm, HttpServletRequest request,WeeklyReport weeklyReport) {

		ActionErrors errors = new ActionErrors();
		Vector workItemList = new Vector();
		int weeklyReportId = weeklyReport.getWeeklyReportId();
		if(weeklyReportId == 0){
			errors.add("errors.rm.weeklyReport.invalid",new ActionError("errors.rm.weeklyReport.invalid"));
			saveErrors(request,errors);
			return "error";
		} else {
			doWeeklyReportActionForm.set("weeklyReportId", new Integer(weeklyReport.getWeeklyReportId()));
			doWeeklyReportActionForm.set("projectId", new Integer(weeklyReport.getProjectId()));
			doWeeklyReportActionForm.set("staffId", new Integer(weeklyReport.getStaffId()));
			doWeeklyReportActionForm.set("totalHoursWorked", new Double(weeklyReport.getTotalHoursWorked()));
			doWeeklyReportActionForm.set("problem",weeklyReport.getProblem());
			doWeeklyReportActionForm.set("comment",weeklyReport.getComment());
			try {
				WeeklyReportWorkItem[] weeklyReportWorkItem = WeeklyReportWorkItemManager.load(weeklyReportId);
				for(int i = 0; i < weeklyReportWorkItem.length; i++) {
					workItemList.add(WorkItemManager.load(weeklyReportWorkItem[i].getWorkItemId()));
				}
				request.setAttribute("workItemList", workItemList);
				request.setAttribute("weeklyReportWorkItem", weeklyReportWorkItem);
			} catch(DataUnavailableException due) {
				log.error(due.getMessage());
			}
			return "rm";
		}
	}
}
